﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VulnDBExplorer.Framework.Impl;
using Luna;
using VulnDB.Action.DataCollectors.Services.Impl;
using Luna.Framework;
using Luna.Framework.Manifest;
using VulnDBExplorer.Services;

namespace VulnDB.Action.DataCollectors.Actions {

	public class ProfileCodebaseAction: DataCollectorAction {
		
		public ProfileCodebaseAction() {
			Name = "ProfileCodebaseAction";
			Text = "&Profile codebase";

			ProfileData = "codebases.txt";
			ExecutionMode = ActionExecutionMode.SeparatedThread;
		}

		public string ProfileData { get; set; }

		protected override void onExecute(object sender, ActionExecutionArgs args) {
			if (args is ActionExecutionArgs) {
				ActionExecutionArgs arg = (ActionExecutionArgs)args;

				CodebaseProfile profiler;
				if (ProfileData.fileExists()) {
					Console.log("Loading CodeProfiler data...");
					profiler = CodebaseProfile.load(ProfileData, arg.Context);
				}
				else
					profiler = new CodebaseProfile(arg.Context);

				profiler.FileEntryProcessStarted += (o, e) => Console.write(e.Filename);
				profiler.FileEntryCompareCompleted += (o, e) => Console.write(".");
				profiler.FileEntryProcessCompleted += (o, e) => Console.writeLine(" OK");

				if (arg.Data is IConfigurationManifest) {
					ICodebase cb =  (ICodebase)Framework.resolveObject(arg.Context, 
						new Uri((arg.Data as IConfigurationManifest).getProperty("codebase", "")), arg.Data);
					if (cb != null) {
						Console.log("Starts profiling codebase: {0}: {1}", cb.Name, cb.Text);
						//IProgressMonitor mon = Application.createProgressMonitor();
						try {
							//mon.start("Processing codebase...", int.MaxValue);
							profiler.addCodebase(cb);
						}
						finally {
							Console.writeLine("Saving CodeProfiler data...");
							profiler.save(ProfileData);
							//mon.stop();
						}
						Console.log("Completed.");
					}
				}
			}
			base.onExecute(sender, args);
		}
	}
}
